package cn.myblog.ainblog.component;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Dovaior
 * @Description
 * @create 2021-04-11 17:20
 **/
@Component
public class LoginHandlerInterceptor implements HandlerInterceptor {
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        Object user = request.getSession().getAttribute("LoginUser");
//        System.out.println("afterCompletion----" + user + " ::: " + request.getRequestURL());
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        Object user = request.getSession().getAttribute("LoginUser");
//        System.out.println("postHandle----" + user + " ::: " + request.getRequestURL());
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object user = request.getSession().getAttribute("LoginUser");
//        System.out.println("preHandle----" + user + " ::: " + request.getRequestURL());
        if (user == null){
            request.setAttribute("msg","无权限请先登录");
            // 获取request返回页面到登录页,并输出提示
            request.getRequestDispatcher("/toLogin").forward(request, response);
            //response.sendRedirect 重定向，无法传输数据
//            response.sendRedirect("/toLogin");
            return false;
        }
        //放行
        return true;
    }
}

